package org.example.im.server.handler.impl;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.im.bean.protocol.request.LoginRequestPacket;
import org.example.im.bean.protocol.response.LoginResponsePacket;
import org.example.im.bean.session.Session;
import org.example.im.common.util.SessionUtil;
import org.example.im.common.util.UUIDUtil;
import org.springframework.stereotype.Component;

/**
 * @author dingrui
 * @since 2022/2/10
 * @description
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class LoginHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestPacket loginRequestPacket) throws Exception {
        Byte version = loginRequestPacket.getVersion();
        String userName = loginRequestPacket.getUserName();
        String password = loginRequestPacket.getPassword();
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(version);
        loginResponsePacket.setUserName(userName);
        if (this.loginCheck(userName, password)) {
            String userId = UUIDUtil.randomUid();
            loginResponsePacket.setUserId(userId);
            loginResponsePacket.setSuccess(true);
            SessionUtil.bindSession(channelHandlerContext.channel(), Session.builder().userId(userId).userName(userName).build());
            System.out.println("[S-Login] 用户[" + userName + "]上线 id=[" + userId + "]");
        } else {
            loginResponsePacket.setSuccess(false);
            loginResponsePacket.setMsg("登录信息校验失败");
        }
        // 登录响应
        channelHandlerContext.channel().writeAndFlush(loginResponsePacket);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        Session session = SessionUtil.getSession(channel);
        SessionUtil.unBindSession(channel);
        System.out.println("[S-Login] 用户[" + session + "]下线");
    }

    // 登录认证
    private boolean loginCheck(final String userName, final String password) {
        // TODO: 2022/2/10 异步 防止整条pipeline职责链阻塞
        return true;
    }
}
